package com.briup.server;

/**
 * @Classname ServerImpl
 * @Description TODO
 * @Date 2023/11/20 22:12
 * @Created by 崔宗祺
 * @Version v1.0.0
 */


import com.briup.Configuration;
import com.briup.entity.Environment;
import com.briup.support.ConfigurationAware;
import com.briup.support.PropertiesAware;
import com.briup.util.Log;

import java.io.File;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Server接口是物联网数据中心项目网络模块中服务端的规范
 * 该模板负责与客户端进行通信接收信息
 * 并且利用DBStore模块的功能将接收的数据进行持久化操作
 */
public class ServerImpl implements Server, PropertiesAware, ConfigurationAware {
    private ServerSocket server;
    private int port;
    private Log log;
    private DBStore store;


    /**
     * 接收网络模块客户端的连接，要求一直接收连接，每当有一个客户端连接到服务端
     * 后，服务端就创建一个线程来接收客户端发送过来的数据。接收完毕后调用入库模块
     * 将接收的数据保存到数据库中
     */
    @Override
    public void receive() throws Exception {
        ExecutorService service = Executors.newFixedThreadPool(50);
        server = new ServerSocket(port);
        log.info("服务器启动成功，等待客户端链接！");
        while (true) {
            Socket socket = server.accept();
            String ip = socket.getInetAddress().toString();
            if (socket != null) {
                log.info("客户端链接成功，IP:" + ip);
            }
            service.submit(() -> {
                try {
                    //创建对象输入流  包装流
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    //接收数据
                    List<Environment> list = (List<Environment>) ois.readObject();
                    log.info("服务器接收到的数据：" + list.size());
                    log.info("准备入库");
                    //入库
                    store.saveDB(list);
                    log.info("入库成功");
                    //关闭资源
                    ois.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /**
     * 关闭网络模块服务端，停止接收来自网络模块客户端的连接
     */
    @Override
    public void shutdown() throws Exception {
        if (server != null) {
            server.close();
        }
    }

    @Override
    public void init(Properties properties) throws Exception {
        port = Integer.parseInt(properties.getProperty("port"));

    }

    @Override
    public void setConfiguration(Configuration configuration) throws Exception {
        log = configuration.getLogger();
        store = configuration.getDbStore();
    }
}
